package com.zhaoyu.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhaoyu.model.article.pojos.ApAuthor;
import com.zhaoyu.model.common.dtos.ResponseResult;
import com.zhaoyu.model.common.enums.AppHttpCodeEnum;
import com.zhaoyu.model.user.dtos.UserRelationDto;
import com.zhaoyu.model.user.pojos.ApUser;
import com.zhaoyu.model.user.pojos.ApUserFan;
import com.zhaoyu.model.user.pojos.ApUserFollow;
import com.zhaoyu.user.feign.article.ArticleFeign;
import com.zhaoyu.user.mapper.ApUserFanMapper;
import com.zhaoyu.user.mapper.ApUserFollowMapper;
import com.zhaoyu.user.mapper.ApUserMapper;
import com.zhaoyu.user.service.ApUserFollowService;
import com.zhaoyu.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserFollowServiceImpl implements ApUserFollowService {

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private ApUserFollowMapper apUserFollowMapper;

    @Autowired
    private ApUserFanMapper apUserFanMapper;

    @Override
    public ResponseResult follow(UserRelationDto userRelationDto) {
        // 检查参数
        if (userRelationDto.getOperation() == null || userRelationDto.getOperation() < 0 || userRelationDto.getOperation() > 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (userRelationDto.getAuthorId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"文章作者信息不能为空");
        }
        // 获取文章作者
        Integer followId = null;
        ApAuthor apAuthor = articleFeign.findByIdApAuthor(userRelationDto.getAuthorId());
        if (apAuthor != null){
            followId = apAuthor.getUserId();
        }
        if (followId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关注人不存在");
        }else {
            Integer userId = AppThreadLocalUtils.getUserId();
            if (userId != null){
                if (userRelationDto.getOperation() == 0){
                    // 如果当前操作是0 创建数据(app用户关注信息和app的用户粉丝信息)
                    return followByUserId(userId,followId,userRelationDto.getArticleId());
                }else {
                    // 如果当前操作是1 删除数据(app用户关注信息和app的用户粉丝信息)
                    return followCancelByUserId(userId,followId);
                }
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            }
        }
    }

    /**
     * 取消关注的处理逻辑
     *      如果当前操作是1 删除数据(app用户关注信息和app的用户粉丝信息)
     */
    private ResponseResult followCancelByUserId(Integer userId, Integer followId) {
        // 先查再删
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().
                                    eq(ApUserFollow::getUserId, userId).
                                    eq(ApUserFollow::getFollowId, followId));
        if (apUserFollow == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"未关注");
        }else {
            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().
                                  eq(ApUserFan::getUserId, followId).
                                  eq(ApUserFan::getFansId, userId));
            if (apUserFan != null){
                // 删除App用户粉丝信息
                if (userId != null){
                    apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery().
                                    eq(ApUserFan::getUserId,followId).
                                    eq(ApUserFan::getFansId,userId));
                }
                // 删除App用户关注信息
                apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery().
                                   eq(ApUserFollow::getUserId,userId).
                                   eq(ApUserFollow::getFollowId,followId));
            }
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }

    /**
     * 处理关注的操作
     *      如果当前操作是0 创建数据(app用户关注信息和app的用户粉丝信息)
     */
    private ResponseResult followByUserId(Integer userId, Integer followId, Long articleId) {
        // 判断当前关注人是否存在
        ApUser followUser = apUserMapper.selectById(userId);
        if (followUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关注用户不存在");
        }
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().
                                    eq(ApUserFollow::getUserId, userId).
                                    eq(ApUserFollow::getFollowId, followId));
        if (apUserFollow == null){
            // 保存数据 ap_user_follow(APP用户关注信息表) ap_user_fan(APP用户粉丝信息表)
            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().
                                  eq(ApUserFan::getUserId, followId).
                                  eq(ApUserFan::getFansId, userId));
            // 保存App用户粉丝信息
            if (apUserFan == null){
                apUserFan = new ApUserFan();
                apUserFan.setUserId(followId); // 用户ID
                apUserFan.setFansId(userId.longValue()); // 粉丝ID
                apUserFan.setFansName(followUser.getName()); // 粉丝昵称
                apUserFan.setLevel((short)0); // 粉丝昵称
                apUserFan.setIsDisplay(true); // 是否可见我动态
                apUserFan.setIsShieldLetter(false); // 是否屏蔽私信
                apUserFan.setIsShieldComment(false); // is_shield_comment
                apUserFan.setCreatedTime(new Date()); // 创建时间
                apUserFanMapper.insert(apUserFan);
            }
            // 保存APP用户关注信息
            apUserFollow = new ApUserFollow();
            apUserFollow.setUserId(userId); // 用户ID
            apUserFollow.setFollowId(followId); // 关注作者ID
            apUserFollow.setCreatedTime(new Date()); // 创建时间
            apUserFollow.setIsNotice(true); // 是否动态通知
            apUserFollow.setLevel((short)1); // 关注度
            apUserFollowMapper.insert(apUserFollow);
            // TODO 记录关注文章的行为
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            // 已关注
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"已关注");
        }
    }

}